package cn.tedu.knows.faq.service.impl;


import cn.tedu.knows.commons.exception.ServiceException;
import cn.tedu.knows.commons.model.*;
import cn.tedu.knows.faq.kafka.QuestionProducer;
import cn.tedu.knows.faq.mapper.QuestionMapper;
import cn.tedu.knows.faq.mapper.QuestionTagMapper;
import cn.tedu.knows.faq.mapper.UserQuestionMapper;
import cn.tedu.knows.faq.service.IQuestionService;
import cn.tedu.knows.faq.service.ITagService;
import cn.tedu.knows.faq.vo.QuestionVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-11-26
 */
@Service
@Slf4j
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {


    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public PageInfo<Question> getMyQuestion(String username,
                                            Integer pageNum, Integer pageSize) {
        // 先根据用户名查询用户对象
        User user = getUser(username);
        // QueryWrapper类定义查询条件
        QueryWrapper<Question> query = new QueryWrapper<>();
        query.eq("user_id", user.getId());
        query.eq("delete_status", 0);
        query.orderByDesc("createtime");
        // 只要在需要进行分页的查询执行之前编写下面代码就能实现分页
        // startPage方法参数([页码],[每页条数])
        // 注意 页码从1开始
        PageHelper.startPage(pageNum, pageSize);
        List<Question> list = questionMapper.selectList(query);
        // 返回之前将list中所有问题对象的tags属性赋值
        for (Question q : list) {
            List<Tag> tags = tagNamesToTags(q.getTagNames());
            q.setTags(tags);
        }
        // 修改分页查询的返回值
        return new PageInfo<>(list);
    }

    // 获得tagService依赖,因为我们需要它来获得包含所有标签的Map缓存
    @Autowired
    private ITagService tagService;

    // 将tagNames转换为List<Tag>的方法
    private List<Tag> tagNamesToTags(String tagNames) {
        // tagNames="Java基础,Java SE,面试题"
        String[] names = tagNames.split(",");
        // names={"Java基础","Java SE","面试题"}
        // 获得包含所有标签的Map
        Map<String, Tag> tagMap = tagService.getTagMap();
        // 实例化一个List用于保存查询获得出的标签对象
        List<Tag> tags = new ArrayList<>();
        for (String name : names) {
            // 获得标签名称对应的标签对象
            Tag t = tagMap.get(name);
            tags.add(t);
        }
        return tags;
    }

    @Autowired
    private QuestionTagMapper questionTagMapper;
    @Autowired
    private UserQuestionMapper userQuestionMapper;

    @Override
    // 添加事务注解
    // 实现效果是当前方法中所有数据库操作要么都执行要么都不执行
    // 只要方法运行过程中发生异常,那么已经执行的sql语句都会回滚
    @Transactional
    public void saveQuestion(QuestionVO questionVO, String username) {
        // 1.根据用户名查询用户对象
        User user = getUser(username);
        // 2.将用户选中的所有标签拼接为一个字符串
        // {"Java基础","Java SE","面试题"}
        StringBuilder builder = new StringBuilder();
        for (String tagName : questionVO.getTagNames()) {
            builder.append(tagName).append(",");
        }
        // Java基础,Java SE,面试题,
        // 删除拼接的字符串最后的字符既最后多余的","
        String tagNames = builder.deleteCharAt(builder.length() - 1)
                .toString();
        // 3.实例化Question对象,收集所有数据库中的信息
        Question question = new Question()
                .setTitle(questionVO.getTitle())
                .setContent(questionVO.getContent())
                .setUserNickName(user.getNickname())
                .setUserId(user.getId())
                .setCreatetime(LocalDateTime.now())
                .setStatus(0)
                .setPageViews(0)
                .setPublicStatus(0)
                .setDeleteStatus(0)
                .setTagNames(tagNames);
        // 4.执行新增Question
        int num = questionMapper.insert(question);
        if (num != 1) {
            throw new ServiceException("数据库忙");
        }
        // 5.新增问题和标签的关系
        // 因为要获得标签名对应的id,所以先将包含所有标签的Map获取过来
        Map<String, Tag> tagMap = tagService.getTagMap();
        // 遍历当前问题选中的所有标签的数组
        for (String tagName : questionVO.getTagNames()) {
            // 根据标签名称获得标签对象
            Tag t = tagMap.get(tagName);
            QuestionTag questionTag = new QuestionTag()
                    .setQuestionId(question.getId())
                    .setTagId(t.getId());
            num = questionTagMapper.insert(questionTag);
            if (num != 1) {
                throw new ServiceException("数据库忙");
            }
            log.debug("新增了问题和标签的关系:{}", questionTag);
        }
        // 6.新增问题和讲师的关系
        Map<String, User> teacherMap = new HashMap<>();
        // 利用Ribbon向sys模块发请求获得所有讲师
        String url = "http://sys-service/v1/users/master";
        User[] teachers = restTemplate.getForObject(
                url, User[].class);
        for (User u : teachers) {
            teacherMap.put(u.getNickname(), u);
        }
        for (String nickname : questionVO.getTeacherNicknames()) {
            User teacher = teacherMap.get(nickname);
            UserQuestion userQuestion = new UserQuestion()
                    .setQuestionId(question.getId())
                    .setUserId(teacher.getId())
                    .setCreatetime(LocalDateTime.now());
            num = userQuestionMapper.insert(userQuestion);
            if (num != 1) {
                throw new ServiceException("数据库忙");
            }
            log.debug("新增了问题和讲师的关系:{}", userQuestion);
        }
        questionProducer.sendQuestion(question);
    }

    @Resource
    private QuestionProducer questionProducer;

    @Override
    public PageInfo<Question> getTeacherQuestions(String username, Integer pageNum, Integer pageSize) {
        // 根据用户名获得用户信息
        User user = getUser(username);
        // 设置分页条件
        PageHelper.startPage(pageNum, pageSize);
        // 执行查询
        List<Question> list = questionMapper
                .findTeacherQuestions(user.getId());
        // 遍历查询结果将每个问题对应的标签赋值
        for (Question q : list) {
            List<Tag> tags = tagNamesToTags(q.getTagNames());
            q.setTags(tags);
        }
        // 返回任务列表
        return new PageInfo<>(list);
    }

    @Override
    public Question getQuestionById(Integer id) {
        // 根据id查询Question基本信息
        Question question = questionMapper.selectById(id);
        // 将查询到的Question对象所有标签属性赋值
        List<Tag> tags = tagNamesToTags(question.getTagNames());
        question.setTags(tags);
        // 别忘了返回question!!!
        return question;
    }

    @Override
    public Integer countQuestionsByUserId(Integer userId) {
        return questionMapper.countQuestionsByUserId(userId);
    }

    @Override
    public PageInfo<Question> getQuestions(Integer pageNum, Integer pageSize) {
        // 分页查询设置
        PageHelper.startPage(pageNum, pageSize);
        List<Question> list = questionMapper.selectList(null);
        return new PageInfo<>(list);
    }

    @Resource
    private RestTemplate restTemplate;

    // 根据用户名获得用户对象的方法,方法内部使用Ribbon调用sys模块实现
    private User getUser(String username) {
        String url = "http://sys-service/v1/auth/user?username={1}";
        User user = restTemplate.getForObject(
                url, User.class, username);
        return user;
    }


}
